<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="850px"
  >
    <div class="form-box">
      <el-form
        ref="form"
        :model="form"
        :inline="true"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="收支类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择收支类型" >
            <el-option
              v-for="dict in type"
              :key="dict.value"
              :label="dict.name"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账单类型" prop="bookType">
          <el-select v-model="form.bookType" filterable placeholder="请选择账单类型" >
            <el-option
              v-for="bill in billTypeList"
              :key="bill.id"
              :label="bill.bookType"
              :value="bill.bookType"
            />
          </el-select>
        </el-form-item>
        <!-- <span v-if="billTypeConfig&&billTypeConfig.length">
          <span v-for="custom in billTypeConfig" :key="custom.id">
            <el-form-item :label="custom.name" :prop="custom.key" v-if="custom.isShow">
              <el-input v-model="form[custom.key]" :placeholder="`请填写${custom.name}`" />
            </el-form-item>
          </span>
        </span> -->
        <el-form-item label="对方名称" prop="duifangmingcheng">
          <el-input v-model="form.duifangmingcheng" placeholder="请输入对方名称" />
        </el-form-item>
        <el-form-item label="对方账户" prop="duifangzhanghu">
          <el-input v-model="form.duifangzhanghu" placeholder="请输入对方账户" />
        </el-form-item>
        <el-form-item label="本方名称" prop="benfangmingcheng">
          <el-input v-model="form.benfangmingcheng" placeholder="请输入本方名称" />
        </el-form-item>
        <el-form-item label="本方账户" prop="benfangzhanghu">
          <el-input v-model="form.benfangzhanghu" placeholder="请输入本方账户" />
        </el-form-item>
        <el-form-item label="金额" prop="jine">
          <el-input v-model="form.jine" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="经办人" prop="jingbanren">
          <el-input v-model="form.jingbanren" placeholder="请输入经办人" />
        </el-form-item>
        <el-form-item label="复核人" prop="fuheren">
          <el-input v-model="form.fuheren" placeholder="请输入复核人" />
        </el-form-item>
        <el-form-item label="明细" prop="mingxi">
          <el-input
              v-model="form.mingxi"
              type="textarea"
              placeholder="账单详细说明"
              :rows="4"
              style="width:600px"
            />
        </el-form-item>
        <el-form-item label="备注" prop="beizhu">
          <el-input
              v-model="form.beizhu"
              type="textarea"
              placeholder="账单详细说明"
              :rows="4"
              style="width:600px"
            />
        </el-form-item>
     
        <el-row>
          <el-form-item label="图片" >
            <el-upload
              :action="uploadImgUrl"
              :file-list="imgShowList"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-exceed="uploadNumber"
              :multiple="true"
              :drag="true"
              :on-success="handleUploadSuccess"
              :limit="50"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-row>

        <div class="center">
          <el-button @click="close()">取消</el-button>
          <el-button type="primary" @click="submitForm('form')" v-loading="loading">提交</el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import financeApi from "@/api/financeCenter/index.js";
import { getToken } from "@/utils/auth";
import jizhangbenApi from "@/api/financeCenter/jizhangben.js";
export default {
  name: "addFina",
  data() {
    return {
      dialogVisible: false,
      loading: false,
      type: [
        {
          name: "收入",
          value: 1
        },
        {
          name: "支出",
          value: 2
        }
      ],
      billTypeList: [],
      billTypeConfig: null, //自定义字段配置
      title: "新增账单",
      isEdit: false,
      uploadImgUrl: "",
      imgShowList: [],
      newImages: [],
      imgFileList: [],
      // 表单参数
      form: {
        type: '',
        bookType:'',
        duifangmingcheng:'',
        duifangzhanghu:'',
        benfangmingcheng:'',
        benfangzhanghu:'',
        jine:'',
        jingbanren:'',
        fuheren:'',
        mingxi:'',
        beizhu:'',
        img:'',
      },
      headers:{},
      rules: {
        type: [
          { required: true, message: "请选择收支类型", trigger: "change" }
        ],
        bookType: [
          { required: true, message: "请选择账单类型", trigger: "change" }
        ],
        jine: [
          { required: true, message: "请输入金额", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    // 打开弹窗
    open(flag, data) {
      this.getTypeList();
      this.newImages = [];
      this.imgShowList = [];
      this.imgFileList = [];
      if (flag == "edit") {
        this.title = "修改账单";
        this.isEdit = true;
        this.handleUpdate(data);
      } else {
        this.isEdit = false;
      }
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.reset();
      });
    },

    // 重置
    reset() {
      this.form = {
        type: '',
        bookType:'',
        duifangmingcheng:'',
        duifangzhanghu:'',
        benfangmingcheng:'',
        benfangzhanghu:'',
        jine:'',
        jingbanren:'',
        fuheren:'',
        mingxi:'',
        beizhu:'',
        img:'',
      };
      this.$refs.form.resetFields();
    },
    // 获取账单类型列表
    getTypeList() {
     
      jizhangbenApi.getTypeList().then(res => {
        this.billTypeList = res.rows;

        if(res.rows.length==0){
          this.$message.error('请先配置账单类型！')
        }
      });
    },
  
 
    /** 查询详情进行回显 */
    handleUpdate(row) {
      const id = row.id || null;
      jizhangbenApi.tallyBookInfoById(id).then(res=>{
        this.form = {...res.data}
        if(this.form.img){
          this.imgShowList = JSON.parse(this.form.img)
          this.imgFileList = JSON.parse(this.form.img)

        }
      })

    },
    submitForm(formName) {
      this.$refs["" + formName].validate(valid => {
        if (valid) {
          // 拼接新上传的图片
          if (this.newImages && this.newImages.length) {
           
            let newArr = [];
            this.newImages.forEach(img => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath
              });
            });
            this.form.img = JSON.stringify(this.imgFileList.concat(newArr));
          } else {
            this.form.img = JSON.stringify(this.imgFileList);
          }
          if (this.isEdit) {
            // 编辑
            jizhangbenApi.editTallyBook(this.form).then(res => {
            
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.$parent.search();
            });

          } else {
            // 新增
            //console.log(this.form);
            jizhangbenApi.addTallyBook(this.form).then(res => {
          
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.$parent.search();
            });
          }
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter(t => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 详情图片删除
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function(element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function(element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url]
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传50张图片");
    },
    close() {
      this.dialogVisible = false;
    }
  }
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

/deep/ .el-upload-dragger{
  width: 150px;
  height: 150px;
}
</style>
